// SoundServices.ts
// type AudioEventCallback = () => void;

export class SoundService {
  private audioContext: WechatMiniprogram.InnerAudioContext | null = null;
  private static instance: SoundService;

  public src = '';

  public justPlayOne = false;

  constructor(src: string, justPlayOne = false) {
    this.justPlayOne = justPlayOne;
    this.init(src);
    return this;
  }

  // 单例模式（可选）
  public static getInstance(): SoundService {
    const _this = this;
    if (!SoundService.instance) {
      SoundService.instance = new SoundService(_this.src);
    }
    return SoundService.instance;
  }

  /**
   * 初始化音频实例
   * @param src 本地音频路径（相对路径示例：'audio/click.mp3'）
   */
  public init(src: string): void {
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.src = src;
    this.setupEventListeners();
  }

  // 事件监听（TypeScript类型强化）
  private setupEventListeners(): void {
    this.audioContext?.onPlay(() => console.log('[Audio] Play start'));
    this.audioContext?.onError((err) =>
      console.error(`[Audio Error] ${err.errCode}:${err.errMsg}`));
    this.audioContext?.onEnded(() => this.justPlayOne ? this.destroy() : '');
  }

  // 播放控制方法
  public play(): void {
    this.audioContext?.play();
  }

  /** 独立播放 */
  public playFast(): void {
    this.audioContext?.stop()
    this.audioContext?.play();
  }

  public pause(): void {
    this.audioContext?.pause();
  }

  public stop(): void {
    this.audioContext?.stop();
    this.destroy();
  }

  // 销毁实例（iOS兼容性处理）[3](@ref)
  public destroy(): void {
    if (this.audioContext) {
      this.audioContext.offPlay();
      this.audioContext.offError();
      this.audioContext.destroy();
      this.audioContext = null;
    }
  }
}

export default SoundService;
